<template>
  <div class="pb-1">
    <div ref="poleInfo" class="scrollY px-3 pt-3" style="max-height: 600px;">
      <dialog-bg :height="600"></dialog-bg>
      <el-form class="ur-form " :inline="true" :model="poleGroup" ref="poleForm">
        <fieldset class="mb-2">
          <legend class="w80">灯杆信息</legend>
          <el-tooltip :content="errors.first('boxNo')" :value="errors.has('boxNo')" :manual="true">
            <el-form-item label="控制箱编号" label-width="120px" required :class="{'is-error':errors.has('boxNo')||hasBoxNo}">
              <el-autocomplete class="w150" size="small" v-model="boxNo" :fetch-suggestions="queryBox" @select="selectBox" @blur="boxNoChange"
                v-validate="'required|max:23'" name="boxNo" :disabled="poleId?true:false" :clearable="true">
                <template slot-scope="{item}">
                  <div >{{item.No}}</div>
                </template>
              </el-autocomplete>
            </el-form-item>
          </el-tooltip>
          <el-tooltip :content="errors.first('poleNo')" :value="errors.has('poleNo')&&scrollVal<100" :manual="true">
            <el-form-item label="灯杆编号" label-width="120px" required :class="{'is-error':errors.has('poleNo')}">
              <el-input class="w150" size="small" v-model="poleGroup.No" v-validate="'required|max:44'" name="poleNo"></el-input>
            </el-form-item>
          </el-tooltip>
          <el-tooltip :content="errors.first('InstallPosition')" :value="errors.has('InstallPosition')&&scrollVal<100" :manual="true">
            <el-form-item label="安装地址" label-width="120px" :class="{'is-error':errors.has('InstallPosition')}">
              <el-input class="w150" size="small" v-model="poleGroup.InstallPosition" v-validate="'max:44'" name="InstallPosition"></el-input>
            </el-form-item>
          </el-tooltip>
          <el-tooltip :content="errors.first('RoadSection')" :value="errors.has('RoadSection')&&scrollVal<100" :manual="true">
            <el-form-item label="所属路段" label-width="120px" :class="{'is-error':errors.has('RoadSection')}" required>
              <el-input class="w150" size="small" v-model="poleGroup.RoadSection" v-validate="'required|max:44'" name="RoadSection"></el-input>
            </el-form-item>
          </el-tooltip>
          <el-tooltip :content="errors.first('PoleLngLat')" :value="errors.has('PoleLngLat')&&scrollVal<140" :manual="true">
            <el-form-item label="经纬度" label-width="120px" :class="{'is-error':errors.has('PoleLngLat')}">
              <input type="hidden" v-model="poleGroup.Lng" >
              <input type="hidden" v-model="poleGroup.Lat"  >
              <el-input  style="width: 320px" size="small" v-model="poleGroup.PoleLngLat" name="PoleLngLat"  @change="changeLngLat('pole',poleGroup.PoleLngLat)"></el-input>
              <el-button class="ur-btn ur-btn-primary w110" @click="showMap=true,mapByType='light'"><i class="iconfont icon-gis"></i>获取经纬度</el-button>
            </el-form-item>
          </el-tooltip>
          <el-form-item label="灯杆材质" label-width="120px">
            <el-select class="w150" size="small" v-model="poleGroup.Material">
              <el-option v-for="(item,index) in global.poleMaterials" :key="index+1" :label="item" :value="index+1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="灯杆类型" label-width="120px">
            <el-select class="w150" size="small" v-model="poleGroup.PoleType">
              <el-option v-for="(item,index) in global.PoleTypes" :key="index+1" :label="item" :value="index+1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="照明类型" label-width="120px">
            <el-select class="w150" size="small" v-model="poleGroup.LightType">
              <el-option v-for="(item,index) in global.LightTypes" :key="index+1" :label="item" :value="index+1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="光源类型" label-width="120px">
            <el-select class="w150" size="small" v-model="poleGroup.LightSourceType">
              <el-option v-for="(item,index) in global.LightSourceTypes" :key="index+1" :label="item" :value="index+1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属开关" label-width="120px">
            <el-select class="w150" size="small" v-model="poleGroup.SwitchNo" @change="switchNoSelect">
              <el-option v-for="index in 6" :key="index" :label="index" :value="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="灯盏数" label-width="120px">
            <el-input type="number" class="w150" v-model="lamps"  size="small" min="1"></el-input>
          </el-form-item>
          <el-form-item label="生产厂家" label-width="120px">
            <el-input class="w150" size="small" v-model="poleGroup.Manufacturer"></el-input>
          </el-form-item>
          <el-tooltip class="item" :content="errors.first('RunDate')" :value="errors.has('RunDate')" :manual="true">
            <el-form-item label="安装日期" label-width="120px" required :class="{'is-error':errors.has('RunDate')}">
              <el-date-picker type="date" placeholder="选择日期"  value-format="yyyy-MM-dd" style="width: 150px;" size="small" v-model="poleGroup.RunDate" v-validate="'required'" name="RunDate"></el-date-picker>
            </el-form-item>
          </el-tooltip>
          <el-form-item label="高架名称" label-width="120px" v-if="poleGroup.LightType==1">
            <el-input class="w150" v-model="poleGroup.OverheadName"  size="small"></el-input>
          </el-form-item>
          <el-form-item label="地道名称" label-width="120px"  v-if="poleGroup.LightType==2">
            <el-input class="w150" v-model="poleGroup.TunnelName"  size="small"></el-input>
          </el-form-item>
          <el-form-item class="mb-0" label="是否安装控制器" label-width="120px">
            <el-select class="w150" size="small" v-model="poleGroup.ControlInstalled">
              <el-option label="是" :value="1"></el-option>
              <el-option label="否" :value="0"></el-option>
            </el-select>
          </el-form-item>
          <!--附件-->
          <el-form-item label="选择附件" label-width="120px" label-position="right" class="w300 mb-0" >
            <div class="p_relative ur-file w150">
              <input class=" file" type="file" style="line-height: 20px;" accept=".png,.jpg,jpeg,.pdf" @change="changeFiles">
            </div>
            <el-button style="margin-top: 3px;" round class="ur-btn-round ur-btn ur-btn-primary" v-if="files.length" @click="showCarousel=true">
              <i class="iconfont icon-xianshi txt_blue2"></i>图片预览
            </el-button>
          </el-form-item>
        </fieldset>
        <!--灯具信息-->
        <fieldset class="mb-2" v-for="(Lamp,index) in LampList">
          <legend class="w80">灯具{{index+1}}信息</legend>
          <el-tooltip :content="errors.first('LampNo'+index)" :value="errors.has('LampNo'+index)" :manual="true">
            <el-form-item label="灯具编号" label-width="120px" required :class="{'is-error':errors.has('LampNo'+index)}">
              <el-input class="w150" size="small" v-model="Lamp.No" v-validate="'required|max:44'" :name="'LampNo'+index"></el-input>
            </el-form-item>
          </el-tooltip>
          <el-form-item  label="额定功率" label-width="120px">
            <el-input class="w150" size="small" v-model="Lamp.Power"></el-input>
          </el-form-item>
          <el-form-item  label="型号" label-width="120px">
            <el-input class="w150" size="small" v-model="Lamp.Model"></el-input>
          </el-form-item>
          <el-form-item class="mb-0" label="相位"  label-width="120px">
            <el-select class="w150" size="small" v-model="Lamp.Phase">
              <el-option label="未知" value="未知"></el-option>
              <el-option label="A" value="A"></el-option>
              <el-option label="B" value="B"></el-option>
              <el-option label="C" value="C"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item class="mb-0" label="生产厂家" label-width="120px">
            <el-input style="width: 435px;" size="small" v-model="Lamp.Manufacturer"></el-input>
          </el-form-item>
        </fieldset>
        <!--终端控制器-->
        <fieldset class="mb-2"  v-if="poleGroup.ControlInstalled==1">
          <legend class="w120">单灯控制器信息</legend>
          <el-form-item label="通讯模式" label-width="120px">
            <el-select class="w150" size="small" v-model="poleGroup.ChannelMode">
              <el-option  v-for="(item,index) in TnChannelModes" :key='index+1' :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-tooltip class="item" :content="errors.first('DevAddr')" :value="errors.has('DevAddr')&&scrollVal>20" :manual="true">
            <el-form-item label="设备地址" label-width="120px" required :class="{'is-error':errors.has('DevAddr')}">
              <el-input class="w150" size="small" v-model="poleGroup.DevAddr"  v-validate="'required|addr16'" name="DevAddr"></el-input>
            </el-form-item>
          </el-tooltip>
          <el-tooltip class="item" :content="errors.first('TnModel')" :value="errors.has('TnModel')&&scrollVal>20" :manual="true">
            <el-form-item label="型号" label-width="120px" required :class="{'is-error':errors.has('TnModel')}">
              <el-input class="w150" size="small" v-model="poleGroup.TnModel"  v-validate="'required'" name="TnModel"></el-input>
            </el-form-item>
          </el-tooltip>
          <el-tooltip :content="errors.first('RtuXh')" :value="errors.has('RtuXh')" :manual="true" >
            <el-form-item label="控制器序号" label-width="120px" required :class="{'is-error':errors.has('RtuXh')}" v-if="poleGroup.ChannelMode==1">
              <el-input class="w150" size="small" v-model="poleGroup.RtuXh"  v-validate="'required'" name="RtuXh"></el-input>
            </el-form-item>
          </el-tooltip>

          <el-form-item label="运营商" label-width="120px" required v-if="poleGroup.ChannelMode!=1">
            <el-select class="w150" size="small" v-model="poleGroup.SimOprators">
              <el-option v-for="(item,index) in global.SimOprators" :key="index" :label="item" :value="item"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="生产厂家" label-width="120px">
            <el-input class="w150" size="small"  v-model="poleGroup.TnManufacturer"></el-input>
          </el-form-item>
          <el-tooltip :content="errors.first('SimNo')" :value="errors.has('SimNo')" :manual="true" v-if="poleGroup.ChannelMode!=1">
            <el-form-item label="sim" label-width="120px" required :class="{'is-error':errors.has('SimNo')}">
              <el-input class="w150" size="small" v-model="poleGroup.SimNo"  v-validate="'required|phone'" name="SimNo"></el-input>
            </el-form-item>
          </el-tooltip>
          <el-tooltip :content="errors.first('NbImei')" :value="errors.has('NbImei')" :manual="true" v-if="poleGroup.ChannelMode!=1">
            <el-form-item class="mb-0" label="imei" label-width="120px" :class="{'is-error':errors.has('NbImei')}" required>
              <el-input class="w150" size="small" v-model="poleGroup.NbImei"   v-validate="'required'"  name="NbImei"></el-input>
            </el-form-item>
          </el-tooltip>
        </fieldset>
      </el-form>
    </div>
    <div class="my-3 text-center">
      <el-button class="ur-btn ur-btn-primary w65" @click="lightSave"><i class="iconfont icon-sure"></i>保存</el-button>
      <el-button class="ur-btn ur-btn-primary w65" @click="reset('poleForm')"><i class="iconfont icon-close3"></i>清空</el-button>
    </div>
    <!--地图-->
    <el-dialog v-el-drag-dialog title="获取位置" :visible.sync="showMap" width="800px" :modal="false" >
      <template v-if="showMap">
        <u-map :iconType="mapByType=='light'?2:3" @getLngLat="getLngLat($event)" :box="box" :pole="poleGroup"></u-map>
      </template>
    </el-dialog>

    <!--图片预览-->
    <div class="w-100 h-100" v-show="showCarousel" style="position: absolute;background: rgba(0,0,0,.4);top:0;left: 0;top:0;z-index: 999;height: 400px;" >
      <file-read :devId="poleId" :files="files" :type="'pole'" :fileDelBtn="limits.indexOf('2_03_02_10')!=-1"
      :delFileUrl="'/Pole/DelFiles'" @closeFileRead="closeFileRead"></file-read>
    </div>
  </div>
</template>

<script>
  import api from 'api/api'
  import fetch from 'api/fetch'
  import uMap from 'base/map/map'
  import dialogBg from "base/dialog-bg"
  import fileRead from "base/fileRead/fileRead2"
  import elDragDialog from 'directive/el-dragDialog'
  import {mapState} from 'vuex'

  export default {
    directives:{elDragDialog},
    components: {uMap,fileRead,dialogBg},
    props: {
      poleId:null
    },
    data() {
      return {
        boxNo:'',
        switchs:[],
        box:{},
        lamps:1,
        poleGroup:{Lat:0,Lng:0,WellLng:0,WellLat:0,PoleLngLat:'0,0',WellLngLat:'0,0',ErectionMode:1,Material:1,PoleType:1,LightType:1,LightSourceType:1,PoleShape:1,WellLayout:1,
          Height:10,BaseForm:1,BaseSpec:1,SwitchNo:1,SwitchXh:'',NbImei:'',NbDeviceId:'',Bulbs:1,ControlInstalled:1,SimOprators:'电信',ChannelMode:1,SpecMaterial:'水泥',Phase:'A',hasWell:false,LampList:[]},
        showMap:false,
        bulbCount:1,
        LampList:[{Phase: 'A'}],
        hasBoxNo:false,
        TnModels:this.global.TnModels,
        boxs:[],
        TnChannelModes:this.global.TnChannelModes,
        scrollVal:0,
        server:api.ajaxServe,
        formData:new FormData(),
        files:[],
        height:0,
        showCarousel:false,
      }
    },
    watch: {
      lamps(val){
        if(val>3){
          this.lamps=3
          this.$message.warning('最多三个灯盏!')
        }else if(val<1){
          this.lamps=1
          this.$message.warning('至少有一个灯盏!')
        }
        if (this.LampList.length < val) {
          for (let i = 0; i < val - this.LampList.length; i++) {
            this.LampList.push({Phase: 'A'})
          }
        } else {
          for (let i = this.LampList.length - val; i > 0; i--) {
            this.LampList.pop()
          }
        }
        /*if(val){
          this.TnModels=[]
          this.global.TnModels.map(r=>{
            let arr=r.split('')
            if (val == arr[arr.length - 1]) {
              this.TnModels.push(r)
            }
          })
        }*/
     },
      /*bulbCount(val){
        if(val>4){
          this.bulbCount=4
          this.$message.warning('最多四个灯泡!')
        }else if(val<1){
          this.bulbCount=1
          this.$message.warning('至少有一个灯泡!')
        }
      },
      boxNo(val){
        if (val) {
          api.fetchSimple('/DevRtu/QueryBoxRtuByNo',{boxNo: val})
            .then(r => {
              if (r.data.length == 0) {
                this.hasBoxNo=true
                // this.$message.warning('控制箱不存在')
              } else {
                this.hasBoxNo=false
                this.box = r.data[0]
                this.$set(this.poleGroup,'RtuId',r.data[0].RtuId)
                this.switchNoSelect()
              }
            })
        }
      }*/
    },
    computed: {
      ... mapState({
        clientHeight: state => state.comm.clientHeight,
        clientWidth: state => state.comm.clientWidth,
        limits:state=>state.user.userInfo.limits
      }),
    },
    methods: {
      closeFileRead(v){
        this.showCarousel=false
      },
      async boxNoChange(){
        let res = await api.fetchSimple('/DevRtu/QueryBoxRtuByNo', {boxNo: this.boxNo})
        if (res.data.length != 0) {
          this.selectBox(res.data[0])
        }
      },
      changeFiles(){
        let files=event.target.files
        for(let i=0;i<files.length;i++){
          this.formData.append('files',files[i])
        }
      },
      uploadFiles(id){
        api.httpFormData('/Pole/SaveFiles?poleId='+id,this.formData)
          .then(r=>{
            this.$emit('close',{})
          })
      },
      changeLngLat(type,lnglat){
        if(lnglat.indexOf(';')!=-1){
          if(type=='pole'){
            this.poleGroup.Lng=lnglat.split(';')[0]
            this.poleGroup.Lat=lnglat.split(';')[1]
          }else{
            this.poleGroup.WellLng=lnglat.split(';')[0]
            this.poleGroup.WellLat=lnglat.split(';')[1]
          }
          this.$validator.errors.remove('PoleLngLat')
          return true
        }else{
          if(type=='pole'){
            this.$validator.errors.add({field: 'PoleLngLat', msg: '格式为经纬;纬度'})
          }else{
            this.$validator.errors.add({field: 'WellLngLat', msg: '格式为经纬;纬度'})
          }
          return false
        }
      },
      getBoxs(){
        api.fetchSimple('/DevRtu/QueryBoxLike',{value: ''})
          .then(r => {
            this.boxs=r.data
          })
      },
      queryBox(queryString, cb){
        let results = queryString ? this.boxs.filter((box,index,boxs)=>{
          return (box.No).toLowerCase().indexOf(queryString.toLowerCase()) === 0
        }) : this.boxs
        cb(results)
      },
      selectBox(item){
        this.box = item
        this.boxNo = item.No
        this.switchNoSelect(this.poleGroup.SwitchNo)
        if (item.RtuInstalled) {
          this.TnChannelModes = global.TnChannelModes
        } else {
          this.poleGroup.ChannelMode=2
          this.TnChannelModes = [{id:2,name:'NB'}]
          this.TnChannelModes.splice(0,0)
        }
      },
      lightSave(){
        this.$validator.validateAll().then((res) => {
          if (res) {
            this.poleGroup['Lamps'] = this.lamps
            if(!this.poleId){//新增
              this.poleGroup['BoxId']=this.box.Id
              this.poleGroup['BoxNo']=this.box.No
              this.poleGroup['AreaId']=this.box.AreaId
            }
            this.poleGroup.WellInstalled = this.poleGroup.hasWell ? 1 : 0
            // this.poleGroup.Bulbs = this.bulbCount
            this.poleGroup.LampList = this.LampList
            api.fetch('/Pole/Save',this.poleGroup)
              .then(async r=>{
                if(r!=''){
                  // this.$message.success('保存成功')
                  // this.queryPole()
                  if (this.formData.getAll('files').length) {
                    await this.uploadFiles(this.poleId||r.data)
                  }else{
                    this.$emit('close',{})
                  }
                }
              })
          }
        })
      },
      reset(formName) {
        // this.$refs[formName].resetFields()
        this.poleGroup={Lat:0,Lng:0,WellLng:0,WellLat:0,PoleLngLat:'0,0',WellLngLat:'0,0',ErectionMode:1,Material:1,PoleType:1,LightType:1,LightSourceType:1,PoleShape:1,WellLayout:1,
          BaseForm:1,BaseSpec:1,SwitchNo:1,SwitchXh:'',NbImei:'',NbDeviceId:'',Bulbs:1,ControlInstalled:1,SimOprators:'电信',ChannelMode:1,SpecMaterial:'水泥'}
      },
      getLngLat(v) {
        if (this.mapByType == 'light') {
          this.poleGroup['PoleLngLat'] = v.lng + '；' + v.lat
          this.poleGroup['Lat'] = v.lat
          this.poleGroup['Lng'] = v.lng
        }else{
          this.poleGroup['WellLngLat'] = v.lng + '；' + v.lat
          this.poleGroup['WellLat'] = v.lat
          this.poleGroup['WellLng'] = v.lng
        }
        this.showMap = false
      },
      queryPoleById(){
        fetch.queryPoleById(this.poleId)
          .then(r=>{
            let data = r.data[0]
            this.poleGroup = data
            this.files = r.Files||[]
            // this.files.splice(0,0)
            this.boxNo = data.BoxNo
            this.queryBoxRtu(data.BoxId)
            this.bulbCount = data.Bulbs||0
            this.lamps = this.poleGroup.Lamps
            this.LampList = this.poleGroup.LampList
            this.$set(this.poleGroup, 'hasWell', data.WellInstalled==1? true : false)
            this.$set(this.poleGroup, 'PoleLngLat', data.Lng + ';' + data.Lat)
            this.$set(this.poleGroup, 'WellLngLat', data.WellLng + ';' + data.WellLat)
          })
      },
      queryBoxRtu(id) {
        let _this = this
        fetch.queryBoxById(id)
          .then(r => {
            let data = r.data[0]
            _this.box = data
          })
      },
      querySwitch(){
        fetch.querySwitch({BoxId:this.pole.BoxId})
          .then(r=>{
            this.switchs=r.data

          })
      },
      switchNoSelect(val){
        let boxId=this.box.Id||this.poleGroup.BoxId
        fetch.GetSwitchXh(boxId,val)
          .then(r=>{
            this.poleGroup.SwitchXh=r.data
          })
      },
    },
    created() {
      if(this.poleId){
        this.queryPoleById()
      }else{
        this.getBoxs()
      }
    },
    mounted() {
      let pole =this.$refs.poleInfo
      pole.addEventListener('scroll', ()=>{
        this.scrollVal =pole.scrollTop
      })
    }
  }
</script>
<style  lang="stylus" rel="stylesheet/stylus">
  #lightTable.el-table{border-radius: 0;
  .cell{padding: 0;}
  td{padding:0;border-color: #c4c4c4;}
  .el-table__body-wrapper{border-color: #c4c4c4;border-top:1px solid #c4c4c4}
  }
  #poleForm .ur-form .el-form-item{margin-bottom: 5px;}
</style>
